package main;

import org.lwjgl.input.Mouse;
import org.lwjgl.opengl.GL11;

/**
 * Example 1-3 (and 2-1)
 * 
 * Displays a rotating square.
 * 
 * Original file: double.c
 * 
 * @author Ciardhubh
 */
public class Main extends Base {

    /**
     * Current rectangle angle.
     */
    private float spin = 0.0f;
    /**
     * Determines whether the rectangle is supposed to spin. Used to emulate the idle function of
     * GLUT.
     */
    private boolean spinning = true;

    public static void main(String[] args) {
        Main example_1_3 = new Main();
        example_1_3.go();
    }

    @Override
    protected void init() {
        GL11.glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
        GL11.glShadeModel(GL11.GL_FLAT);

        // From original reshape(int w, int h), as there is no resizing in our display.
        GL11.glViewport(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT);
        GL11.glMatrixMode(GL11.GL_PROJECTION);
        GL11.glLoadIdentity();
        GL11.glOrtho(-50.0, 50.0, -50.0, 50.0, -1.0, 1.0);
        GL11.glMatrixMode(GL11.GL_MODELVIEW);
        GL11.glLoadIdentity();
    }

    @Override
    protected void render() {
        GL11.glClear(GL11.GL_COLOR_BUFFER_BIT);
        GL11.glPushMatrix();
            GL11.glRotatef(spin, 0.0f, 0.0f, 1.0f);
            GL11.glColor3f(1.0f, 1.0f, 1.0f);
            GL11.glRectf(-25.0f, -25.0f, 25.0f, 25.0f);
        GL11.glPopMatrix();
        // glutSwapBuffers(); is not needed as double buffering is standard in LWJGL.
    }

    /**
     * Was: void mouse(int button, int state, int x, int y) 
     * Was: void spinDisplay(void)
     */
    @Override
    protected void logic(long timeDelta) {
        // From: void mouse(int button, int state, int x, int y) 
        if (Mouse.isButtonDown(0)) {
            // Left button pressed.
            spinning = true;
        } else if (Mouse.isButtonDown(2) || Mouse.isButtonDown(1)) {
            // Center or right button pressed.
            spinning = false;
        }

        // From: void spinDisplay(void)
        if (spinning) {
            spin = spin + 0.2f * timeDelta;
            if (spin > 360.0f) {
                spin = spin - 360.0f;
            }
        }
        // glutPostRedisplay(); is not needed due to continuous display loop in LWJGL.
    }
}